﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TccServicos.Models;
using TccServicos.Util;

namespace TccServicos.Controllers
{
    public class FotoAddController : ApiController
    {
        #region Atributos
        private string sThread = "";
        #endregion

        [HttpPost]
        public int SaveFotoAdd()
        {
            sThread = Util.Util.NextHex(4);
            string nomeFuncao = string.Format("{0} [{1}]", "SaveFotoAdd", sThread);

            HttpRequestMessage request = this.Request; 
            if (!request.Content.IsMimeMultipartContent())
            {
                Log.GravarLog("nao");
            }
            else
            {
                Log.GravarLog("sim");
            }

            Log.GravarLog("TestByte function entered");
            //test to see if i get anything, not sure how to do this
            byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
            Log.GravarLog(data.ToString());

            var objeto = data;

            try
            {
                if (!Validacao.ObjetoValido(null))
                {
                    Log.GravarLog(string.Format("{0}: {1}", nomeFuncao, Validacao.objetoInvalido));
                }

                string jsonEntrada = JsonConvert.SerializeObject(objeto, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

                Log.GravarLog(string.Format("{0}: {1}", nomeFuncao, jsonEntrada));

                using (adoteEntities contexto = new adoteEntities())
                {
                    var objetoSalvar = new CADASTRO_FOTO
                    {
                        ID_FOTO = 0,
                        NOME = "nome",
                        TIPO = "jpeg",
                        FOTO = objeto,
                    };
                    contexto.CADASTRO_FOTO.Add(objetoSalvar);
                    contexto.SaveChanges();

                    Log.GravarLog(string.Format("{0}: {1}", nomeFuncao, Validacao.salvoComSucesso));
                    return objetoSalvar.ID_FOTO;
                }
            }
            catch (Exception ex)
            {
                Log.GravarLog(string.Format("{0} Erro: {1}", nomeFuncao, ex.ToString()));
                return 0;
            }
        }
    }
}
